<template>
  <div class="app-container">
    <el-form :inline="true" ref="refForm" :model="form">
      <el-form-item label="查询时间" prop="time">
        <el-date-picker
          v-model="form.time"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="submitFilterForm">搜索</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-download" @click="exportHandle">导出</el-button>
      <el-button @click="resetForm('refForm')">重置</el-button>
    </el-form>
    <div class="height-300" ref="financeChart">
      <financial-analyze-chart :x-data="xData" :yData="yData"></financial-analyze-chart>
    </div>
    <!--
          show-summary
      :summary-method="getSummaries"
      -->
    <el-table
      border
      :data="tableData"
      v-loading="loading"
      :span-method="getSpanMethod"
      element-loading-text="加载中..."
      class="el-table-align-center my-table-footer">
      <el-table-column label="时间" prop="date" width="180" align="center">
      </el-table-column>
      <!-- <el-table-column label="三方支付"> -->
        <el-table-column v-if="item.value>0" :label="item.title" align="center"
                         v-for="(item,index) in consts.RECHARGE_THIRD_TYPE_NAMES" :key="item.value"
                         :prop="String(item.value)">
          <template slot-scope="{row}">
            {{row[item.value] | currency}}
          </template>
        </el-table-column>
      <!-- </el-table-column> -->
      <!-- <el-table-column label="转账入款"> -->
        <el-table-column v-if="item.value>0" :label="item.title" align="center"
                         v-for="(item,index) in consts.RECHARGE_TRANSFER_TYPE_NAMES" :key="item.value">
          <template slot-scope="{row}">
            {{row[item.value] | currency}}
          </template>
        </el-table-column>
      <!-- </el-table-column> -->
    </el-table>

    <!--<div class="pagination-container">-->
    <!--<el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"-->
    <!--:current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"-->
    <!--:layout="gridLayout" :total="tableData.total">-->
    <!--</el-pagination>-->
    <!--</div>-->
  </div>
</template>
<script>
  import {getFinanceAnalyzeApi as listApi,exportFinanceAnalysis} from "@/services/api/operational";
  import {grid} from '@/build'
  import financialAnalyzeChart from '../components/financeAnalyzeChart'

  export default {
    name: "finance-analyze",
    mixins: [grid],
    components: {
      financialAnalyzeChart
    },
    data() {
      // 本月时间本月1号至当前时间
      const monthTime = [moment().startOf('month').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      return {
        tableData: [],
        xData: [],
        yData: [],
        form: {
          time: monthTime,
          proxy: undefined,
          domain: undefined
        },
        filters: {
          stime: moment(monthTime[0]).valueOf(),
          etime: moment(monthTime[1]).valueOf() +  86399999,
          size: 20,
          page: 1
        },

      }
    },
    methods: {
      selfResetForm(formName) {
        this.resetForm(formName);
        this.submitFilterForm();
      },
      submitFilterForm() {
        const {time} = this.form;
        let stime = undefined, etime = undefined;
        if (!_.isUndefined(time) && _.isArray(time)) {
          stime = moment(time[0]).valueOf();
          etime = moment(time[1]).valueOf() +  86399999;
        }
        this.filters = {stime, etime, project: consts.PLATFROM_PREFIX}
        this.gridSearch()
      },
      getSummaries(param) {
        const {columns, data} = param;
        const sums = [];
        columns.forEach((column, index) => {
          const values = data.map(item => Number(item[column.property]));
          if (index === 0) {
            sums[index] = '汇总';
            return;
          } else {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
          }
        });
        return sums;
      },
      getSpanMethod({row, column, rowIndex, columnIndex}) {
        if (rowIndex == this.tableData.length - 2 && columnIndex == 0) {
          return [2, 1]
        }
        if (rowIndex == this.tableData.length - 1) {
          if (columnIndex == 0) {
            return [0, 0]
          } else if (columnIndex == 1) {
            return [1, 9]
          } else if (columnIndex == 10) {
            return [1, 3]
          } else {
            return [0, 0]
          }
        }
      },
      getChartData(data) {
        let yArr = []
        _.forEach(consts.RECHARGE_THIRD_TYPE_NAMES, value => {
          if (value.title != '全部') yArr.push(Object.assign(value, {type: 'bar', name: value.title, data: []}))
        })
        _.forEach(consts.RECHARGE_TRANSFER_TYPE_NAMES, value => {
          if (value.title != '全部') yArr.push(Object.assign(value, {type: 'bar', name: value.title, data: []}))
        })
        _.forEach(data, value => {
          _.forEach(yArr, item => {
            item.data.unshift(value[item.value])
          })
        })
        this.yData = yArr
      },
       //导出
      exportHandle() {
        let {stime, etime,page} = this.filters
        let ajaxData = {stime, etime,page}
        let filename = '金流分析明细报表.csv';
        let header = ['时间', '网银支付', '支付宝支付', '微信支付','快捷支付','银联扫码','银行卡转账','支付宝转账','微信转账']
        let filterField = ['date', '1', '2', '3','24','5','7','8','9']
        exportFinanceAnalysis(ajaxData).then(([result, data]) => {

      if (result) {
            let exportData = this.responseFormatter(data);
            console.log(exportData)
            // return
            this.export2Excel(header, filterField, exportData, filename)

          } else {
            this.$message({message: '导出失败,' + data.message, type: "warning"})
          }
        })
      },
      responseFormatter(data) {
           let result = [];
          let sortData = [];
          this.xData = []
          _.forIn(data, (value, key) => {
            result.push({...(value), date: key})
            this.xData.push(key)
          })
          // console.log(sortData,result)
          sortData = _.sortBy(result, (item) => {
            return item.date;
          }).reverse();

          _.forEach(sortData,(item,index)=>{
            for (let prop in item) {
              if(prop=='date') return;
              item[prop] = _.currency(item[prop])
            }
          });

          return [...sortData]
      },
    },
    mounted() {
      this.bindGet(listApi, 'tableData', {
        action: 'getGrid',
        sendingData: 'filters',
        format: data => {
          let result = [];
          let sortData = [];
          this.xData = []
          _.forIn(data, (value, key) => {
            result.push({...value, date: key})
            this.xData.push(key)
          })
          // console.log(sortData,result)
          sortData = _.sortBy(result, (item) => {
            return item.date;
          }).reverse();
          let sum = {
            date: '汇总'
          }
          _.forEach(sortData, (item, index) => {
            _.forIn(item, (value, key) => {
              if (key != 'date') if (index == 0) {
                sum[key] = value
              } else {
                sum[key] += value
              }
            })
          })
          let total = {date: '汇总'}
          let fixkey1 = '', fixkey2 = ''
          _.forIn(sum, (value, key) => {
            if (_.find(consts.RECHARGE_THIRD_TYPE_NAMES, item => {
              return item.value == key
            })) {
              if (key == 1) {
                total[key] = sum[key]
                fixkey1 = key
              } else {
                total[fixkey1] += sum[key]
              }
            }
            if (_.find(consts.RECHARGE_TRANSFER_TYPE_NAMES, item => {
              return item.value == key
            })) {
              if (key == 17) {
                total[key] = sum[key]
                fixkey2 = key
              } else {
                total[fixkey2] += sum[key]
              }
            }
          })
          this.getChartData(sortData)
          console.log([...sortData, sum, total])
          return [...sortData, sum, total]
        }
      });
      this.submitFilterForm();
    }

  }
</script>

<style scoped lang="scss">
  .my-table-footer /deep/ {
    .el-table__row {
      &:last-child, &:nth-last-child(2) {
        background-color: #f5f7fa;
      }
    }
  }
</style>
